<template>
  <div class="kpis-container">
    <el-card class="kpis-card">
      <template #header>
        <div class="card-header">
          <span>指标管理</span>
          <el-button type="primary" @click="handleAdd">新增指标</el-button>
        </div>
      </template>

      <el-form :inline="true" class="search-form">
        <el-form-item label="指标名称">
          <el-input v-model="searchForm.name" placeholder="请输入指标名称" clearable />
        </el-form-item>
        <el-form-item label="指标类型" style="width: 250px;">
          <el-select v-model="searchForm.type" placeholder="请选择指标类型" clearable>
            <el-option label="业绩指标" value="performance" />
            <el-option label="行为指标" value="behavior" />
            <el-option label="能力指标" value="ability" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="kpiList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="指标名称" min-width="120" />
        <el-table-column prop="type" label="指标类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">{{ getTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重" width="100">
          <template #default="{ row }">
            {{ row.weight }}%
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="standard" label="评分标准" min-width="200" show-overflow-tooltip />
        <el-table-column prop="department" label="适用部门" min-width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 指标表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增指标' : '编辑指标'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="kpiForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="指标名称" prop="name">
          <el-input v-model="kpiForm.name" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="指标类型" prop="type">
          <el-select v-model="kpiForm.type" placeholder="请选择指标类型">
            <el-option label="业绩指标" value="performance" />
            <el-option label="行为指标" value="behavior" />
            <el-option label="能力指标" value="ability" />
          </el-select>
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input-number
            v-model="kpiForm.weight"
            :min="1"
            :max="100"
            :step="1"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="适用部门" prop="departmentIds">
          <el-tree-select
            v-model="kpiForm.departmentIds"
            :data="departmentOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            multiple
            placeholder="请选择适用部门"
          />
        </el-form-item>
        <el-form-item label="指标描述" prop="description">
          <el-input
            v-model="kpiForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入指标描述"
          />
        </el-form-item>
        <el-form-item label="评分标准" prop="standard">
          <el-input
            v-model="kpiForm.standard"
            type="textarea"
            :rows="3"
            placeholder="请输入评分标准"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getKPIPage } from '@/api/kpis'

interface KPI {
  id: number
  name: string
  type: 'performance' | 'behavior' | 'ability'
  weight: number
  description: string
  standard: string
  department: string
  departmentIds: number[]
}

interface Template {
  id: number
  name: string
  type: string
  description: string
  kpis: { id: number; name: string; weight: number }[]
}

interface Department {
  id: number
  name: string
  children?: Department[]
}

const activeTab = ref('list')
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref<FormInstance>()

const searchForm = reactive({
  name: '',
  type: ''
})

const kpiForm = reactive({
  id: 0,
  name: '',
  type: '',
  weight: 0,
  description: '',
  standard: '',
  departmentIds: [] as number[]
})

const rules = {
  name: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择指标类型', trigger: 'change' }],
  weight: [{ required: true, message: '请输入权重', trigger: 'blur' }],
  departmentIds: [{ required: true, message: '请选择适用部门', trigger: 'change' }],
  description: [{ required: true, message: '请输入指标描述', trigger: 'blur' }],
  standard: [{ required: true, message: '请输入评分标准', trigger: 'blur' }]
}

// 模拟数据
const mockKPIs: KPI[] = [
  {
    id: 1,
    name: '项目完成质量',
    type: 'performance',
    weight: 30,
    description: '项目交付的质量评估',
    standard: '5分：优秀，4分：良好，3分：合格，2分：需改进，1分：不合格',
    department: '技术部',
    departmentIds: [2]
  },
  {
    id: 2,
    name: '团队协作能力',
    type: 'behavior',
    weight: 20,
    description: '与团队成员的协作表现',
    standard: '5分：表现突出，4分：表现良好，3分：表现一般，2分：需改进，1分：表现差',
    department: '所有部门',
    departmentIds: [1]
  }
]

const mockTemplates: Template[] = [
  {
    id: 1,
    name: '技术部绩效模板',
    type: '通用模板',
    description: '适用于技术部门的绩效考核',
    kpis: [
      { id: 1, name: '项目完成质量', weight: 30 },
      { id: 2, name: '团队协作能力', weight: 20 }
    ]
  }
]

const mockDepartments: Department[] = [
  {
    id: 1,
    name: '总公司',
    children: [
      { id: 2, name: '技术部' },
      { id: 3, name: '人力资源部' }
    ]
  }
]

const kpiList = ref<KPI[]>(mockKPIs)
const templates = ref<Template[]>(mockTemplates)
const departmentOptions = ref<Department[]>(mockDepartments)

function getTypeTag(type: string) {
  const map: Record<string, string> = {
    performance: 'success',
    behavior: 'warning',
    ability: 'info'
  }
  return map[type] || 'info'
}

function getTypeText(type: string) {
  const map: Record<string, string> = {
    performance: '业绩指标',
    behavior: '行为指标',
    ability: '能力指标'
  }
  return map[type] || '未知'
}

async function loadKPIs() {
  loading.value = true
  try {
    const response = await getKPIPage({
      current: currentPage.value,
      size: pageSize.value,
      name: searchForm.name,
      type: searchForm.type
    })
    kpiList.value = response.records
    total.value = response.total
  } catch (error) {
    console.error('获取指标列表失败:', error)
    ElMessage.error('获取指标列表失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  loadKPIs()
}

function handleReset() {
  searchForm.name = ''
  searchForm.type = ''
  handleSearch()
}

function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(kpiForm, {
    id: 0,
    name: '',
    type: '',
    weight: 0,
    description: '',
    standard: '',
    departmentIds: []
  })
}

function handleAdd() {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

function handleEdit(row: KPI) {
  dialogType.value = 'edit'
  Object.assign(kpiForm, {
    id: row.id,
    name: row.name,
    type: row.type,
    weight: row.weight,
    description: row.description,
    standard: row.standard,
    departmentIds: row.departmentIds
  })
  dialogVisible.value = true
}

function handleCopy(row: KPI) {
  dialogType.value = 'add'
  Object.assign(kpiForm, {
    ...row,
    id: 0,
    name: `${row.name} - 副本`
  })
  dialogVisible.value = true
}

function handleDelete(row: KPI) {
  ElMessageBox.confirm(
    '确定要删除该指标吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // TODO: 实现删除指标功能
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    // TODO: 实现保存指标功能
    ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
    dialogVisible.value = false
    loadKPIs()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

function handleUseTemplate(template: Template) {
  // TODO: 实现使用模板功能
  ElMessage.info('使用模板功能开发中')
}

function handleEditTemplate(template: Template) {
  // TODO: 实现编辑模板功能
  ElMessage.info('编辑模板功能开发中')
}

function handleSizeChange(val: number) {
  pageSize.value = val
  loadKPIs()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  loadKPIs()
}

// 初始加载
loadKPIs()
</script>

<style scoped>
.kpis-container {
  padding: 20px;
}

.kpis-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-fill-color-blank);
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.template-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.template-card {
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  transition: all 0.3s;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.template-header {
  padding: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.template-content {
  padding: 15px;
}

.template-desc {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 10px;
}

.template-kpis {
  list-style: none;
  padding: 0;
  margin: 0;
}

.template-kpis li {
  padding: 5px 0;
  color: var(--el-text-color-regular);
}

.template-footer {
  padding: 15px;
  border-top: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

:deep(.el-table th) {
  /* background-color: #f5f7fa; */
  color: #606266;
  font-weight: 600;
}

:deep(.el-table__fixed-right .el-table__fixed-body-wrapper .el-table__body) {
  background-color: #f5f7fa;
}

:deep(.el-table__fixed-right .el-table__fixed-header-wrapper .el-table__header) {
  background-color: #f5f7fa;
}
</style>